#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import opengate as gate

if __name__ == "__main__":
    # create the simulation
    sim = gate.Simulation()

    # options
    sim.visu = False
    sim.visu_type = "vrml"
    sim.output_dir = "./output"
    sim.progress_bar = True

    # units
    m = gate.g4_units.m
    cm = gate.g4_units.cm
    cm3 = gate.g4_units.cm3
    keV = gate.g4_units.keV
    MeV = gate.g4_units.MeV
    mm = gate.g4_units.mm
    Bq = gate.g4_units.Bq
    gcm3 = gate.g4_units.g / cm3

    # world
    world = sim.world
    world.size = [1 * m, 1 * m, 1 * m]
    world.material = "G4_AIR"

    # waterbox
    waterbox = sim.add_volume("Box", "waterbox")
    waterbox.size = [40 * cm, 40 * cm, 40 * cm]
    waterbox.translation = [0 * cm, 0 * cm, 25 * cm]
    waterbox.material = "G4_WATER"
    waterbox.color = [0, 0, 1, 1]

    # physics
    sim.physics_manager.physics_list_name = "G4EmStandardPhysics_option4"
    sim.physics_manager.set_production_cut("world", "all", 10 * mm)
    sim.physics_manager.set_production_cut("waterbox", "all", 0.01 * mm)

    # source
    source = sim.add_source("GenericSource", "mysource")
    source.particle = "gamma"
    source.energy.type = "gauss"
    source.energy.mono = 10 * MeV
    source.energy.sigma_gauss = 1 * MeV
    source.position.type = "disc"
    source.position.radius = 3 * mm
    source.position.translation = [0, 0, 0]
    # Uncomment the following line to rotate the source
    # source.position.rotation = Rotation.from_euler("x", 33, degrees=True).as_matrix()
    source.direction.type = "momentum"
    source.direction.momentum = [0, 0, 1]
    source.n = 5000

    # stats
    stats = sim.add_actor("SimulationStatisticsActor", "stats")
    stats.track_types_flag = True
    stats.output_filename = "ex1_stats.txt"

    # dose actor 1: depth edep
    depth_dose = sim.add_actor("DoseActor", "depth_edep")
    depth_dose.attached_to = "waterbox"
    depth_dose.output_filename = "ex1_gamma_depth.mhd"
    depth_dose.spacing = [40 * cm, 40 * cm, 4 * mm]
    depth_dose.size = [1, 1, 100]
    depth_dose.edep_uncertainty.active = True

    # dose actor 2: edep profile
    lateral_edep = sim.add_actor("DoseActor", "lateral_edep")
    lateral_edep.attached_to = "waterbox"
    lateral_edep.output_filename = "ex1_gamma_lateral.mhd"
    lateral_edep.spacing = [0.5 * mm, 40 * cm, 40 * cm]
    lateral_edep.size = [100, 1, 1]
    lateral_edep.edep_uncertainty.active = True

    # run
    sim.run()

    # print stat file
    print(stats)
